package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("添加Dish"+dishDTO);
        dishService.save(dishDTO);
        String key = "dish_"+dishDTO.getCategoryId();
        redisTemplate.delete(key);
        return Result.success();
    }


    @GetMapping("/page")
    public Result selectByPage(DishPageQueryDTO dishPageQueryDTO){
        log.info("分页查询：{}",dishPageQueryDTO);
        PageResult pageResult = dishService.selectByPage(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping
    public Result deleteByIds(@RequestParam Integer[] ids){
        log.info("批量删除菜品：{}",ids);
        dishService.deleteByIds(ids);
        deleteRedis("dish_*");
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
        log.info("根据id查询菜品DISH:{}",id);
        DishVO dishVO = dishService.selectByIdWithFlavors(id);
        return Result.success(dishVO);
    }

    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品信息：{}",dishDTO);
        dishService.update(dishDTO);
        deleteRedis("dish_*");
        return Result.success();
    }

    @GetMapping("/list")
    public Result selectByCategoryId(@RequestParam("categoryId") Integer id){
        log.info("根据分类id查询菜品:{}",id);
        List<DishVO> list = dishService.selectBYCategoryId(id);
        return Result.success(list);
    }

    @PostMapping("/status/{status}")
    public Result updateStatus(@PathVariable Integer status,@RequestParam Integer id){
        log.info("修改菜品售卖状态 id：{} status：{}",id,status);
        dishService.updateStatus(status,id);
        deleteRedis("dish_*");
        return Result.success();
    }

    private void deleteRedis(String pattern){
        Set key = redisTemplate.keys(pattern);
        redisTemplate.delete(key);
    }
}
